package com.begamer.card.controller;

import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.begamer.card.cache.Cache;
import com.begamer.card.cache.PlayerInfo;
import com.begamer.card.common.dao.hibernate.CommDao;
import com.begamer.card.common.util.MD5;
import com.begamer.card.common.util.RequestUtil;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.common.util.binRead.UnLockData;
import com.begamer.card.json.ErrorJson;
import com.begamer.card.json.KYLoginJson;
import com.begamer.card.json.PlayerElement;
import com.begamer.card.json.RecvPSData;
import com.begamer.card.json.UserResultJson;
import com.begamer.card.json.command.LoginJson;
import com.begamer.card.json.command.RegistJson;
import com.begamer.card.json.command2.PlayerResultJson;
import com.begamer.card.log.ErrorLogger;
import com.begamer.card.log.PlayerLogger;
import com.begamer.card.model.dbservice.UserService;
import com.begamer.card.model.pojo.User;

/**
 * 
 * @ClassName: UserController
 * @author 国实
 * @date Feb 25, 2011 9:45:56 AM
 * 
 */
public class UserController extends AbstractMultiActionController {

	private Logger logger = Logger.getLogger(UserController.class);
	private Logger playlogger = PlayerLogger.logger;
	private Logger errorlogger = ErrorLogger.logger;
	
	@Autowired
	private UserService userService;
	@Autowired
	private CommDao commDao;
	
	/** 渠道sdk用户前缀:91,同步推,PP,当乐,itools,蜂巢,云点友游 **/
	private static final String[] SkdNames = { "91_", "TB_", "PP_", "DL_",
			"IT_", "GC_", "CP_", "AS_", "CoP_", "BD_", "KY_", "XY_", "GCIOS_",
			"HM_" };

	/**
	 * 登录
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView login(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			logger.info("login:" + request.getRemoteAddr() + ","
					+ request.getSession().getId());
			// 检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null) {
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			// 获取参数
			LoginJson lj = JSONObject.toJavaObject(jsonObject, LoginJson.class);
			PlayerResultJson prj = new PlayerResultJson();
			if (lj != null) {
				String uid = lj.uid;
				String psd = lj.psd;
				int otherInfo = lj.other;
				String platform = lj.platform;
				String nickName = lj.nickname;
				// 验证该用户是否存在
				User user = userService.getUserByName(uid);
				if (user == null) {
					// 渠道玩家注册新用户
					boolean canReg = false;
					for (String prefix : SkdNames) {
						if (uid.startsWith(prefix)) {
							canReg = true;
							break;
						}
					}
					if (canReg) {
						if (prj.errorCode == 0) {
							String ip = request.getRemoteAddr();
							if (commDao.reg(uid, psd, nickName, ip, platform) == 0) {
								prj.errorCode = 7;
							}
						}
					} else {
						prj.errorCode = -4;
					}
				} else {
					// 验证密码是否正确
					if (!user.getPassword().equals(psd)) {
						errorlogger.info("uid:" + uid + ",psd:" + psd);
						prj.errorCode = -5;
					}
				}
				if (prj.errorCode == 0) {
					int userId = userService.getUserByNameAndPassword(uid, psd)
							.getId();
					int playerId = commDao.getPlayerIdByUserId(userId);
					if (otherInfo == 1) {
						PlayerInfo pi = Cache.getInstance()
								.getPlayerInfoByMemory(playerId);
						if (pi != null && pi.willOnline()) {
							prj.mark = 0;
						} else {
							prj.mark = 1;
						}
					}
					PlayerInfo pi = Cache.getInstance().login(playerId,
							request.getSession());
					if (pi != null) {
						PlayerElement pj = new PlayerElement();
						if (pi.player.getBattlePower() == 0) {
							pi.calBattlePower();
						}
						pj.setData(pi.player);
						List<PlayerElement> list = new ArrayList<PlayerElement>();
						list.add(pj);
						prj.list = list;
						// 模块解锁
						int mission = pi.player.getMissionId();
						int lv = pi.player.getLevel();
						String[] s = UnLockData.getUnLockStrByMethod(mission,
								lv);
						prj.s = s;
						playlogger.info("用户" + uid + "登录,玩家"
								+ pi.player.getId() + "登录服务器");
					} else {
						playlogger.info("用户" + uid + "登录失败,服务器玩家已达上限"
								+ Cache.MaxSize);
						prj.errorCode = 1;
					}
				}
			} else {
				prj.errorCode = -1;
			}
			Cache.recordRequestNum(prj);
			String msg = JSON.toJSONString(prj);
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		} catch (Exception e) {
			errorlogger.error(this.getClass().getName() + "->"
					+ Thread.currentThread().getStackTrace()[1].getMethodName()
					+ "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}

	/** PP登录验证 **/
	public ModelAndView preLoginForPP(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			UserResultJson uj = new UserResultJson();
			byte token_key[] = RequestUtil.readStream(request.getInputStream());
			URL url = new URL(
					"http://passport_i.25pp.com:8080/index?tunnel-command=2852126756");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("User_Agent", "25PP");
			conn.setRequestProperty("Connection", "close");
			// 长度是实体的二进制长度
			conn.setRequestProperty("Content-Length", String
					.valueOf(token_key.length));
			conn.getOutputStream().write(token_key);
			conn.getOutputStream().flush();
			conn.getOutputStream().close();
			InputStream ppserver_InputStream = conn.getInputStream();
			RecvPSData recvJson = null;
			if (ppserver_InputStream != null) {
				byte ppsbuff[] = RequestUtil.readStream(ppserver_InputStream);
				String recvjson = new String(ppsbuff, "UTF-8");
				recvjson = "{" + recvjson + "}"; // 连接成标准json字符串
				JSONObject jsonObject = JSONObject.parseObject(recvjson);
				recvJson = JSONObject
						.toJavaObject(jsonObject, RecvPSData.class);
			}
			// 登录成功
			if (recvJson != null && recvJson.getStatus() == 0) {
				uj.setStatus(1);
				uj.setUserId(recvJson.getUserid() + "");
				uj.setUserName(recvJson.getUsername());
			}
			String msg = JSON.toJSONString(uj);
			logger.info("msg:" + msg);
			RequestUtil.setResult(request, msg);
			return new ModelAndView("/user/result.vm");
		} catch (Exception e) {
			errorlogger.error(this.getClass().getName() + "->"
					+ Thread.currentThread().getStackTrace()[1].getMethodName()
					+ "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}

	/** 快用登录验证 **/
	public ModelAndView preLoginForKY(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			UserResultJson uj = new UserResultJson();
			byte token_key[] = RequestUtil.readStream(request.getInputStream());
			String tokenKey = new String(token_key, Charset.forName("UTF-8"));
			String AppKey = "953cba7b9333fa63b0f9d0c2227453d3";
			// AppKey与tokenKey的MD5值,注意AppKey在前，tokenKey在后,均为小写.
			// 例如：AppKey 为111，tokenKey 为222，则sign 值为md5(111222)生成的32 位十六进制串
			String sign = MD5
					.md5(AppKey.toLowerCase() + tokenKey.toLowerCase())
					.toLowerCase();
			String url = "http://f_signin.bppstore.com/loginCheck.php";
			PostMethod req = new PostMethod(url);
			req.addParameter("tokenKey", tokenKey);
			req.addParameter("sign", sign);
			HttpClient httpclient = new HttpClient();
			int result = httpclient.executeMethod(req);
			if (result == 200) {
				InputStream inputStream = req.getResponseBodyAsStream();
				byte[] resBytes = new byte[0];
				byte[] buff = new byte[256];
				int n = 0;
				while ((n = inputStream.read(buff)) >= 0) {
					int length = resBytes.length;
					byte[] bs = new byte[length + n];
					System.arraycopy(resBytes, 0, bs, 0, length);
					System.arraycopy(buff, 0, bs, length, n);
					resBytes = bs;
				}
				inputStream.close();
				String resStr = new String(resBytes, Charset.forName("UTF-8"));
				logger.info("快用服务器返回:" + resStr);
				KYLoginJson lj = JSON.toJavaObject(JSON.parseObject(resStr),
						KYLoginJson.class);
				// 登录成功
				if (lj.code == 0) {
					uj.setStatus(1);
					uj.setUserId(lj.data.guid);
					uj.setUserName(lj.data.username);
				}
			} else {
				logger.info("快用服务器连接失败:" + result);
			}
			req.releaseConnection();
			String msg = JSON.toJSONString(uj);
			logger.info("msg:" + msg);
			RequestUtil.setResult(request, msg);
			return new ModelAndView("/user/result.vm");
		} catch (Exception e) {
			errorlogger.error(this.getClass().getName() + "->"
					+ Thread.currentThread().getStackTrace()[1].getMethodName()
					+ "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}

	/**
	 * 注册
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView regist(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// 检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if (checkResult != null) {
				return checkResult;
			}
			// 获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			// 获取参数
			RegistJson rj = JSONObject.toJavaObject(jsonObject,
					RegistJson.class);
			ErrorJson rrj = new ErrorJson();
			if (rj != null) {
				String uid = rj.uid;
				String psd = rj.psd;
				String nickname = rj.nickname;
				String ip = request.getRemoteAddr();
				String platform = rj.platform;
				// 验证注册用户名的唯一性
				User user = userService.getUserByName(uid);
				// 可注册
				if (user == null) {
					if (StringUtil.match(uid) || StringUtil.match(psd)) {
						rrj.errorCode = -6;
					}

					if (rrj.errorCode == 0) {
						if (commDao.reg(uid, psd, nickname, ip, platform) == 0) {
							rrj.errorCode = 7;
						}
						playlogger.info("玩家" + uid + "注册");
					}
				}
				// 用户名已被注册
				else {
					rrj.errorCode = -6;
				}
			} else {
				rrj.errorCode = -1;
			}
			Cache.recordRequestNum(rrj);
			String msg = JSON.toJSONString(rrj);
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		} catch (Exception e) {
			errorlogger.error(this.getClass().getName() + "->"
					+ Thread.currentThread().getStackTrace()[1].getMethodName()
					+ "():", e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}

	// /**
	// * 服务器列表
	// * @param request
	// * @param response
	// * @return
	// */
	// public ModelAndView serverList(HttpServletRequest request ,
	// HttpServletResponse response)
	// {
	// try
	// {
	// //检验密钥
	// ModelAndView checkResult = RequestUtil.check(request);
	// if(checkResult != null)
	// {
	// return checkResult;
	// }
	// String msg = ServersData.getServerListJson();
	// logger.info("msg:"+msg);
	// RequestUtil.setResponseMsg(request, msg);
	// return new ModelAndView("/user/result.vm");
	// }
	// catch (Exception e)
	// {
	// errorlogger.error(this.getClass().getName()+"->"+Thread.currentThread().getStackTrace()[1].getMethodName()+"():",e);
	// RequestUtil.removeKey(request);
	// String newKey = RequestUtil.setNewKey(request);
	// RequestUtil.setResult(request, newKey);
	// }
	// return new ModelAndView("/user/result.vm");
	// }

}
